import re
import requests

def parse_m3u8(content, base_url, refer):
    """解析M3U8文件内容"""
    key_url = None
    segments = []
    lines = content.splitlines()
    current_duration = 0
    
    for line in lines:
        line = line.strip()
        
        # 解析加密密钥
        if line.startswith("#EXT-X-KEY"):
            match = re.search(r'URI="([^"]+)"', line)
            if match:
                key_url = resolve_url(match.group(1), base_url, refer)
        
        # 解析片段时长
        elif line.startswith("#EXTINF:"):
            duration = line.replace("#EXTINF:", "").replace(",", "")
            current_duration = float(duration)
        
        # 解析TS片段
        elif line and not line.startswith("#"):
            segment_url = resolve_url(line, base_url, refer)
            segments.append((segment_url, current_duration))
            current_duration = 0
    
    return key_url, segments

def resolve_url(url, base_url, refer):
    """解析相对URL为绝对URL"""
    if url.startswith("http"):
        return url
    elif url.startswith("//"):  # 处理双斜杠开头的URL
        return "http:" + url
    elif url.startswith("/"):
        return base_url + url
    else:
        return refer.rstrip('/') + '/' + url if refer else base_url + '/' + url
    
def download_m3u8(url, referer=None):
    """下载M3U8文件内容"""
    headers = {"Referer": referer} if referer else {}
    response = requests.get(url, headers=headers)
    response.raise_for_status()
    return response.text